package com.jz.community.basecomm.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.jz.community.basecommunity.R;

import java.io.File;
import java.io.FileOutputStream;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Ani on 2017/7/12.
 */

public class RxImageDownload {

    public static Observable<Uri> saveImageAndGetPath(final Context context, final String url, final String title, final int width, final int height ) {
        return Observable.create(new ObservableOnSubscribe<Bitmap>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Bitmap> e) throws Exception {
                Bitmap bitmap = null;
                RequestBuilder<Bitmap> requestBuilder = Glide.with(context)
                        .asBitmap()
                        .load(url);
                bitmap = requestBuilder
                        .submit(width, height)
                        .get();
                if (bitmap == null) {
                    e.onError(new Exception("无法下载到图片"));
                }
                e.onNext(bitmap);
                e.onComplete();
            }
        }).flatMap(new Function<Bitmap, ObservableSource<Uri>>() {
            @Override
            public ObservableSource<Uri> apply(@NonNull Bitmap bitmap) throws Exception {
                File appDir = new File(Environment.getExternalStorageDirectory(), context.getResources().getString(R.string.app_name));
                if (!appDir.exists()) {
                    appDir.mkdir();
                }
                String fileName = title.replace('/', '-') + ".jpg";
                File file = new File(appDir, fileName);
                FileOutputStream fos = new FileOutputStream(file);
                if (bitmap != null) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                }
                Uri uri = Uri.fromFile(file);
                // 通知图库更新
                Intent scannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
                context.sendBroadcast(scannerIntent);
                return Observable.just(uri);
            }
        }).subscribeOn(Schedulers.io());

    }

    public static Observable<Uri> saveImageAndGetPath(final Context context, final String url, final String title) {
        return Observable.create(new ObservableOnSubscribe<Bitmap>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Bitmap> e) throws Exception {
                Bitmap bitmap = null;
                RequestBuilder<Bitmap> requestBuilder = Glide.with(context)
                        .asBitmap()
                        .load(url);
                bitmap = requestBuilder
                        .submit()
                        .get();
                if (bitmap == null) {
                    e.onError(new Exception("无法下载到图片"));
                }
                e.onNext(bitmap);
                e.onComplete();
            }
        }).flatMap(new Function<Bitmap, ObservableSource<Uri>>() {
            @Override
            public ObservableSource<Uri> apply(@NonNull Bitmap bitmap) throws Exception {
                File appDir = new File(Environment.getExternalStorageDirectory(), context.getResources().getString(R.string.app_name));
                if (!appDir.exists()) {
                    appDir.mkdir();
                }
                String fileName = title.replace('/', '-') + ".jpg";
                File file = new File(appDir, fileName);
                FileOutputStream fos = new FileOutputStream(file);
                if (bitmap != null) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                }
                Uri uri = Uri.fromFile(file);
                // 通知图库更新
                Intent scannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
                context.sendBroadcast(scannerIntent);
                return Observable.just(uri);
            }
        }).subscribeOn(Schedulers.io());

    }
}
